<template>
  <div class="zabbix-templates-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容 -->
    <div class="content-wrapper">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <h1><i class="fa fa-file-code"></i> Zabbix模板管理</h1>
          <p>管理Zabbix监控模板，支持模板的查看、导入、导出和配置</p>
        </div>
      </div>

      <!-- 服务器选择和操作栏 -->
      <div class="control-panel glass-effect">
        <div class="server-selection">
          <label>选择Zabbix服务器：</label>
          <el-select
            v-model="selectedZabbixServer"
            placeholder="请选择Zabbix服务器"
            @change="handleServerChange"
            style="width: 300px;"
          >
            <el-option
              v-for="server in zabbixServers"
              :key="server.id"
              :label="`${server.name} (${server.connection_status_display})`"
              :value="server.id"
              :disabled="server.connection_status !== 'connected'"
            />
          </el-select>
        </div>

        <div class="action-buttons">
          <button @click="refreshData" class="glass-button refresh-button" :disabled="loading || !selectedZabbixServer">
            <i class="fa fa-refresh" :class="{ 'fa-spin': loading }"></i>
            刷新数据
          </button>
          <button @click="createTemplate" class="glass-button create-button" :disabled="!selectedZabbixServer">
            <i class="fa fa-plus"></i>
            创建模板
          </button>
          <button @click="importTemplate" class="glass-button import-button" :disabled="!selectedZabbixServer">
            <i class="fa fa-upload"></i>
            导入模板
          </button>
          <button @click="batchImportTemplates" class="glass-button batch-import-button" :disabled="!selectedZabbixServer">
            <i class="fa fa-file-archive-o"></i>
            批量导入
          </button>
          <button @click="exportTemplates" class="glass-button export-button" :disabled="!selectedZabbixServer || selectedTemplates.length === 0">
            <i class="fa fa-download"></i>
            导出模板
          </button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filter-panel glass-effect">
        <div class="search-controls">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索模板名称或描述"
            style="width: 300px;"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <i class="fa fa-search"></i>
            </template>
          </el-input>

          <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 150px;">
            <el-option label="全部" value="" />
            <el-option label="已启用" value="enabled" />
            <el-option label="已禁用" value="disabled" />
          </el-select>

          <el-select v-model="filterType" placeholder="类型筛选" style="width: 150px;">
            <el-option label="全部" value="" />
            <el-option label="系统模板" value="system" />
            <el-option label="自定义模板" value="custom" />
          </el-select>
        </div>
      </div>

      <!-- 模板列表 -->
      <div class="templates-content">
        <!-- 骨架屏加载 -->
        <div v-if="loading" class="skeleton-container">
          <div v-for="i in 8" :key="i" class="skeleton-card glass-effect">
            <div class="skeleton-header">
              <div class="skeleton-text skeleton-title"></div>
              <div class="skeleton-text skeleton-subtitle"></div>
            </div>
            <div class="skeleton-content">
              <div class="skeleton-text"></div>
              <div class="skeleton-text skeleton-short"></div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else-if="filteredTemplates.length === 0" class="empty-state glass-effect">
          <i class="fa fa-file-code"></i>
          <p>暂无模板数据</p>
          <p v-if="!selectedZabbixServer" class="hint">请先选择Zabbix服务器</p>
        </div>

        <!-- 模板卡片网格 -->
        <div v-else class="templates-grid">
          <div
            v-for="template in filteredTemplates"
            :key="template.templateid"
            class="template-card glass-effect"
            :class="{ 'selected': selectedTemplates.includes(template.templateid) }"
            @click="toggleTemplateSelection(template.templateid)"
          >
            <div class="template-header">
              <div class="template-info">
                <h3 class="template-name">{{ template.name }}</h3>
                <p class="template-description">{{ template.description || '无描述' }}</p>
              </div>
              <div class="template-status">
                <span
                  class="status-badge"
                  :class="getTemplateStatusClass(template.status)"
                >
                  {{ getTemplateStatusText(template.status) }}
                </span>
              </div>
            </div>

            <div class="template-stats">
              <div class="stat-item">
                <i class="fa fa-list-alt"></i>
                <span>{{ template.items?.length || 0 }} 监控项</span>
              </div>
              <div class="stat-item">
                <i class="fa fa-bell"></i>
                <span>{{ template.triggers?.length || 0 }} 触发器</span>
              </div>
              <div class="stat-item">
                <i class="fa fa-chart-line"></i>
                <span>{{ template.graphs?.length || 0 }} 图形</span>
              </div>
            </div>

            <div class="template-actions">
              <button @click.stop="viewTemplate(template)" class="action-btn view-btn">
                <i class="fa fa-eye"></i>
                查看详情
              </button>
              <button @click.stop="editTemplate(template)" class="action-btn edit-btn">
                <i class="fa fa-edit"></i>
                编辑
              </button>
              <button @click.stop="cloneTemplate(template)" class="action-btn clone-btn">
                <i class="fa fa-copy"></i>
                克隆
              </button>
              <button @click.stop="exportTemplate(template)" class="action-btn export-btn">
                <i class="fa fa-download"></i>
                导出
              </button>
              <button
                @click.stop="deleteTemplate(template)"
                class="action-btn delete-btn"
                :disabled="template.hosts && template.hosts.length > 0"
              >
                <i class="fa fa-trash"></i>
                删除
              </button>
            </div>

            <div v-if="template.hosts && template.hosts.length > 0" class="linked-hosts">
              <p class="hosts-title">关联主机 ({{ template.hosts.length }}):</p>
              <div class="hosts-list">
                <span
                  v-for="host in template.hosts.slice(0, 3)"
                  :key="host.hostid"
                  class="host-tag"
                >
                  {{ host.name }}
                </span>
                <span v-if="template.hosts.length > 3" class="more-hosts">
                  +{{ template.hosts.length - 3 }} 更多
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && filteredTemplates.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="totalTemplates"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
          background
        />
      </div>
    </div>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="templateDetailVisible"
      :title="`模板详情 - ${selectedTemplate?.name}`"
      width="80%"
      class="glass-dialog template-detail-dialog"
    >
      <div v-if="selectedTemplate" class="template-detail-content">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <label>模板名称:</label>
              <span>{{ selectedTemplate.name }}</span>
            </div>
            <div class="info-item">
              <label>模板ID:</label>
              <span>{{ selectedTemplate.templateid }}</span>
            </div>
            <div class="info-item">
              <label>状态:</label>
              <span
                class="status-badge"
                :class="getTemplateStatusClass(selectedTemplate.status)"
              >
                {{ getTemplateStatusText(selectedTemplate.status) }}
              </span>
            </div>
            <div class="info-item">
              <label>描述:</label>
              <span>{{ selectedTemplate.description || '无描述' }}</span>
            </div>
          </div>
        </div>

        <!-- 监控项列表 -->
        <div class="detail-section">
          <h4>监控项 ({{ selectedTemplate.items?.length || 0 }})</h4>
          <div v-if="selectedTemplate.items && selectedTemplate.items.length > 0" class="items-list">
            <div v-for="item in selectedTemplate.items" :key="item.itemid" class="item-row">
              <div class="item-info">
                <span class="item-name">{{ item.name }}</span>
                <span class="item-key">{{ item.key_ }}</span>
              </div>
              <span class="item-type">{{ getItemType(item.type) }}</span>
            </div>
          </div>
          <div v-else class="no-items">
            暂无监控项
          </div>
        </div>

        <!-- 触发器列表 -->
        <div class="detail-section">
          <h4>触发器 ({{ selectedTemplate.triggers?.length || 0 }})</h4>
          <div v-if="selectedTemplate.triggers && selectedTemplate.triggers.length > 0" class="triggers-list">
            <div v-for="trigger in selectedTemplate.triggers" :key="trigger.triggerid" class="trigger-row">
              <div class="trigger-info">
                <span class="trigger-name">{{ trigger.description }}</span>
                <span class="trigger-expression">{{ trigger.expression }}</span>
              </div>
              <span class="trigger-priority" :class="`priority-${trigger.priority}`">
                {{ getTriggerPriority(trigger.priority) }}
              </span>
            </div>
          </div>
          <div v-else class="no-triggers">
            暂无触发器
          </div>
        </div>

        <!-- 图形列表 -->
        <div class="detail-section">
          <h4>图形 ({{ selectedTemplate.graphs?.length || 0 }})</h4>
          <div v-if="selectedTemplate.graphs && selectedTemplate.graphs.length > 0" class="graphs-list">
            <div v-for="graph in selectedTemplate.graphs" :key="graph.graphid" class="graph-row">
              <div class="graph-info">
                <span class="graph-name">{{ graph.name }}</span>
                <span class="graph-id">ID: {{ graph.graphid }}</span>
              </div>
            </div>
          </div>
          <div v-else class="no-graphs">
            暂无图形
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="`编辑模板 - ${editForm.name}`"
      width="600px"
      class="glass-dialog"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px" class="glass-form">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入模板名称" class="glass-input" />
        </el-form-item>

        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入模板描述"
            class="glass-input"
          />
        </el-form-item>

        <el-form-item label="模板状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" class="glass-select" style="width: 100%;">
            <el-option label="已启用" value="0" />
            <el-option label="已禁用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <button @click="editDialogVisible = false" class="glass-button">取消</button>
          <button @click="confirmEdit" class="glass-button primary" :disabled="editLoading">
            <i v-if="editLoading" class="fa fa-spinner fa-spin"></i>
            {{ editLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </template>
    </el-dialog>

    <!-- 模板克隆对话框 -->
    <el-dialog
      v-model="cloneDialogVisible"
      :title="`克隆模板 - ${cloneForm.sourceName}`"
      width="600px"
      class="glass-dialog"
      :close-on-click-modal="false"
    >
      <el-form :model="cloneForm" :rules="cloneRules" ref="cloneFormRef" label-width="120px" class="glass-form">
        <el-form-item label="源模板名称">
          <el-input v-model="cloneForm.sourceName" disabled class="glass-input" />
        </el-form-item>

        <el-form-item label="新模板名称" prop="name">
          <el-input v-model="cloneForm.name" placeholder="请输入新模板名称" class="glass-input" />
        </el-form-item>

        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="cloneForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入模板描述"
            class="glass-input"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <button @click="cloneDialogVisible = false" class="glass-button">取消</button>
          <button @click="confirmClone" class="glass-button primary" :disabled="cloneLoading">
            <i v-if="cloneLoading" class="fa fa-spinner fa-spin"></i>
            {{ cloneLoading ? '克隆中...' : '克隆' }}
          </button>
        </div>
      </template>
    </el-dialog>

    <!-- 创建模板对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建新模板"
      width="600px"
      class="glass-dialog"
      :close-on-click-modal="false"
    >
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="120px" class="glass-form">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入模板名称" class="glass-input" />
        </el-form-item>

        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入模板描述"
            class="glass-input"
          />
        </el-form-item>

        <el-form-item label="主机组" prop="groups">
          <el-select v-model="createForm.groups" multiple placeholder="请选择主机组" class="glass-select" style="width: 100%;">
            <el-option
              v-for="group in hostGroups"
              :key="group.groupid"
              :label="group.name"
              :value="group.groupid"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <button @click="createDialogVisible = false" class="glass-button">取消</button>
          <button @click="confirmCreate" class="glass-button primary" :disabled="createLoading">
            <i v-if="createLoading" class="fa fa-spinner fa-spin"></i>
            {{ createLoading ? '创建中...' : '创建' }}
          </button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入模板对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入模板"
      width="600px"
      class="glass-dialog import-dialog"
    >
      <div class="import-content">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :before-remove="handleFileRemove"
          accept=".xml,.json"
          drag
        >
          <i class="fa fa-upload"></i>
          <div class="upload-text">
            <p>将模板文件拖拽到此处，或<em>点击上传</em></p>
            <p class="upload-hint">支持 XML 和 JSON 格式的模板文件</p>
          </div>
        </el-upload>

        <div class="import-options">
          <el-checkbox v-model="importOptions.createMissing">创建缺失的主机组</el-checkbox>
          <el-checkbox v-model="importOptions.updateExisting">更新已存在的模板</el-checkbox>
          <el-checkbox v-model="importOptions.deleteMissing">删除缺失的元素</el-checkbox>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <button @click="closeImportDialog" class="glass-button">取消</button>
          <button @click="confirmImport" class="glass-button primary" :disabled="!uploadFile">确认导入</button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量导入模板对话框 -->
    <el-dialog
      v-model="batchImportDialogVisible"
      title="批量导入模板"
      width="600px"
      class="glass-dialog batch-import-dialog"
    >
      <div class="import-content">
        <el-upload
          ref="batchUploadRef"
          :auto-upload="false"
          :on-change="handleBatchFileChange"
          :before-remove="handleBatchFileRemove"
          accept=".zip"
          drag
        >
          <i class="fa fa-file-archive-o"></i>
          <div class="upload-text">
            <p>将ZIP文件拖拽到此处，或<em>点击上传</em></p>
            <p class="upload-hint">支持包含多个XML模板文件的ZIP压缩包</p>
          </div>
        </el-upload>

        <div class="import-options">
          <el-checkbox v-model="batchImportOptions.createMissing">创建缺失的主机组</el-checkbox>
          <el-checkbox v-model="batchImportOptions.updateExisting">更新已存在的模板</el-checkbox>
        </div>

        <div class="batch-import-tips">
          <h4>批量导入说明：</h4>
          <ul>
            <li>上传包含多个XML模板文件的ZIP压缩包</li>
            <li>系统会自动解压并逐个导入所有模板文件</li>
            <li>支持导入完整的模板配置（监控项、触发器、图形等）</li>
            <li>导入过程中如果某个模板失败，不会影响其他模板的导入</li>
          </ul>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <button @click="closeBatchImportDialog" class="glass-button">取消</button>
          <button @click="confirmBatchImport" class="glass-button primary" :disabled="!batchUploadFile">确认导入</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { monitoringApi } from '@/api/monitoring'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref, watch } from 'vue'

// 响应式数据
const loading = ref(false)
const zabbixServers = ref([])
const selectedZabbixServer = ref(null)
const templates = ref([])
const selectedTemplates = ref([])
const searchKeyword = ref('')
const filterStatus = ref('')
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(24)
const totalTemplates = ref(0)
const hostGroups = ref([])

// 对话框状态
const templateDetailVisible = ref(false)
const selectedTemplate = ref(null)
const importDialogVisible = ref(false)
const uploadFile = ref(null)
const uploadRef = ref(null)

// 批量导入相关
const batchImportDialogVisible = ref(false)
const batchUploadFile = ref(null)
const batchUploadRef = ref(null)

// 编辑相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  templateid: '',
  name: '',
  description: '',
  status: '0'
})

const editRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 1, max: 100, message: '模板名称长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 克隆相关
const cloneDialogVisible = ref(false)
const cloneLoading = ref(false)
const cloneFormRef = ref(null)
const cloneForm = ref({
  sourceId: '',
  sourceName: '',
  name: '',
  description: ''
})

const cloneRules = {
  name: [
    { required: true, message: '请输入新模板名称', trigger: 'blur' },
    { min: 1, max: 100, message: '模板名称长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 创建相关
const createDialogVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref(null)
const createForm = ref({
  name: '',
  description: '',
  groups: ['1'] // 默认选择Templates组
})

const createRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 1, max: 100, message: '模板名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  groups: [
    { required: true, message: '请至少选择一个主机组', trigger: 'change' }
  ]
}

// 导入选项
const importOptions = ref({
  createMissing: true,
  updateExisting: false,
  deleteMissing: false
})

// 批量导入选项
const batchImportOptions = ref({
  createMissing: true,
  updateExisting: true
})

// 计算属性
const filteredTemplates = computed(() => {
  let filtered = templates.value

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(template =>
      template.name.toLowerCase().includes(keyword) ||
      (template.description && template.description.toLowerCase().includes(keyword))
    )
  }

  // 状态过滤
  if (filterStatus.value) {
    filtered = filtered.filter(template => {
      if (filterStatus.value === 'enabled') return template.status === '0'
      if (filterStatus.value === 'disabled') return template.status === '1'
      return true
    })
  }

  // 类型过滤
  if (filterType.value) {
    filtered = filtered.filter(template => {
      if (filterType.value === 'system') return template.name.startsWith('Template ')
      if (filterType.value === 'custom') return !template.name.startsWith('Template ')
      return true
    })
  }

  totalTemplates.value = filtered.length

  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 方法
const loadZabbixServers = async () => {
  try {
    const response = await monitoringApi.getZabbixServers()
    if (response.data.success) {
      zabbixServers.value = response.data.data || []

      // 自动选择第一个连接的服务器
      const connectedServer = zabbixServers.value.find(server =>
        server.is_active && server.connection_status === 'connected'
      )
      if (connectedServer) {
        selectedZabbixServer.value = connectedServer.id
        await loadTemplates()
        await loadHostGroups()
      }
    }
  } catch (error) {
    console.error('加载Zabbix服务器失败:', error)
    ElMessage.error('加载Zabbix服务器失败')
  }
}

// 加载主机组列表
const loadHostGroups = async () => {
  if (!selectedZabbixServer.value) return

  try {
    const response = await monitoringApi.getAvailableHostGroups(selectedZabbixServer.value)
    if (response.data.success) {
      hostGroups.value = response.data.data || []
    } else {
      console.error('获取主机组失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取主机组失败:', error)
  }
}

const loadTemplates = async () => {
  if (!selectedZabbixServer.value) return

  loading.value = true
  try {
    const response = await monitoringApi.getZabbixTemplates(selectedZabbixServer.value)
    if (response.data.success) {
      templates.value = response.data.data || []
      console.log('加载模板数据:', templates.value.length, '个模板')
    } else {
      ElMessage.error(response.data.message || '加载模板失败')
    }
  } catch (error) {
    console.error('加载模板失败:', error)
    ElMessage.error('加载模板失败')
  } finally {
    loading.value = false
  }
}

const refreshData = async () => {
  selectedTemplates.value = []
  await loadTemplates()
  ElMessage.success('数据刷新成功')
}

const handleServerChange = async () => {
  selectedTemplates.value = []
  templates.value = []
  if (selectedZabbixServer.value) {
    await loadTemplates()
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handlePageChange = (page: number) => {
  currentPage.value = page
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const toggleTemplateSelection = (templateId: string) => {
  const index = selectedTemplates.value.indexOf(templateId)
  if (index > -1) {
    selectedTemplates.value.splice(index, 1)
  } else {
    selectedTemplates.value.push(templateId)
  }
}

const viewTemplate = (template: any) => {
  selectedTemplate.value = template
  templateDetailVisible.value = true
}



const cloneTemplate = (template: any) => {
  cloneForm.value = {
    sourceId: template.templateid,
    sourceName: template.name,
    name: `${template.name} - 副本`,
    description: template.description || ''
  }
  cloneDialogVisible.value = true
}

const confirmClone = async () => {
  if (!cloneFormRef.value) return

  try {
    await cloneFormRef.value.validate()
    cloneLoading.value = true

    const response = await monitoringApi.cloneZabbixTemplate(
      selectedZabbixServer.value,
      cloneForm.value.sourceId,
      {
        name: cloneForm.value.name,
        description: cloneForm.value.description
      }
    )

    if (response.data.success) {
      ElMessage.success('模板克隆成功')
      cloneDialogVisible.value = false
      await loadTemplates() // 重新加载模板列表
    } else {
      ElMessage.error(response.data.message || '模板克隆失败')
    }
  } catch (error) {
    console.error('克隆模板失败:', error)
    ElMessage.error('克隆模板失败')
  } finally {
    cloneLoading.value = false
  }
}

const deleteTemplate = async (template: any) => {
  try {
    // 显示详细的删除确认信息
    const confirmText = template.hosts && template.hosts.length > 0
      ? `模板 "${template.name}" 正在被 ${template.hosts.length} 个主机使用。\n\n删除模板将影响这些主机的监控功能。\n\n确定要删除吗？此操作不可恢复！`
      : `确定要删除模板 "${template.name}" 吗？\n\n此操作不可恢复！`

    await ElMessageBox.confirm(
      confirmText,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )

    // 执行删除操作
    const response = await monitoringApi.deleteZabbixTemplate(
      selectedZabbixServer.value,
      template.templateid
    )

    if (response.data.success) {
      ElMessage.success('模板删除成功')
      await loadTemplates() // 重新加载模板列表
    } else {
      ElMessage.error(response.data.message || '模板删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败')
    }
    // 用户取消时不显示错误
  }
}

const createTemplate = () => {
  // 重置表单
  createForm.value = {
    name: '',
    description: '',
    groups: ['1'] // 默认选择Templates组
  }
  createDialogVisible.value = true
}

const confirmCreate = async () => {
  if (!createFormRef.value) return

  try {
    await createFormRef.value.validate()
    createLoading.value = true

    const response = await monitoringApi.createZabbixTemplate(
      selectedZabbixServer.value,
      {
        name: createForm.value.name,
        description: createForm.value.description,
        groups: createForm.value.groups.map(groupId => ({ groupid: groupId }))
      }
    )

    if (response.data.success) {
      ElMessage.success('模板创建成功')
      createDialogVisible.value = false
      await loadTemplates() // 重新加载模板列表
    } else {
      ElMessage.error(response.data.message || '模板创建失败')
    }
  } catch (error) {
    console.error('创建模板失败:', error)
    ElMessage.error('创建模板失败')
  } finally {
    createLoading.value = false
  }
}

const importTemplate = () => {
  importDialogVisible.value = true
}

// 导出单个模板
const exportTemplate = async (template: any) => {
  console.log('开始导出模板:', template.name, 'ID:', template.templateid)

  if (!selectedZabbixServer.value) {
    ElMessage.warning('请先选择Zabbix服务器')
    return
  }

  try {
    console.log('调用API导出模板, 服务器ID:', selectedZabbixServer.value, '模板ID:', template.templateid)
    const response = await monitoringApi.exportZabbixTemplate(selectedZabbixServer.value, template.templateid)
    console.log('API响应:', response)

    if (response.data.success) {
      // 创建下载链接
      const blob = new Blob([response.data.data], { type: 'application/xml' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${template.name}_template.xml`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success('模板导出成功')
    } else {
      ElMessage.error(response.data.message || '模板导出失败')
    }
  } catch (error) {
    console.error('导出模板失败:', error)
    ElMessage.error('导出模板失败: ' + error.message)
  }
}

const exportTemplates = async () => {
  if (selectedTemplates.value.length === 0) {
    ElMessage.warning('请先选择要导出的模板')
    return
  }

  try {
    ElMessage.info(`正在导出 ${selectedTemplates.value.length} 个模板...`)

    const templateIds = selectedTemplates.value
    console.log('批量导出模板IDs:', templateIds)

    const response = await monitoringApi.exportZabbixTemplates(selectedZabbixServer.value, templateIds)
    console.log('批量导出响应:', response)

    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/zip' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `zabbix_templates_export_${selectedTemplates.value.length}_${new Date().toISOString().slice(0, 10)}.zip`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(`成功导出 ${selectedTemplates.value.length} 个模板`)

    // 清空选择
    selectedTemplates.value = []

  } catch (error) {
    console.error('批量导出模板失败:', error)
    ElMessage.error(`批量导出模板失败: ${error.response?.data?.message || error.message}`)
  }
}

const handleFileChange = (file: any) => {
  uploadFile.value = file
}

const handleFileRemove = () => {
  uploadFile.value = null
}

// 关闭导入对话框并清理文件选择
const closeImportDialog = () => {
  importDialogVisible.value = false
  uploadFile.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const confirmImport = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先选择要导入的模板文件')
    return
  }

  if (!selectedZabbixServer.value) {
    ElMessage.warning('请先选择Zabbix服务器')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', uploadFile.value.raw)

    const response = await monitoringApi.importZabbixTemplate(selectedZabbixServer.value, formData)
    if (response.data.success) {
      ElMessage.success('模板导入成功')
      closeImportDialog() // 使用统一的关闭函数
      await loadTemplates() // 重新加载模板列表
    } else {
      ElMessage.error(response.data.message || '模板导入失败')
    }
  } catch (error) {
    console.error('导入模板失败:', error)
    ElMessage.error('导入模板失败')
  }
}

// 批量导入相关方法
const batchImportTemplates = () => {
  batchImportDialogVisible.value = true
}

const handleBatchFileChange = (file: any) => {
  batchUploadFile.value = file
}

const handleBatchFileRemove = () => {
  batchUploadFile.value = null
}

// 关闭批量导入对话框并清理文件选择
const closeBatchImportDialog = () => {
  batchImportDialogVisible.value = false
  batchUploadFile.value = null
  if (batchUploadRef.value) {
    batchUploadRef.value.clearFiles()
  }
}

const confirmBatchImport = async () => {
  if (!batchUploadFile.value) {
    ElMessage.warning('请先选择要导入的ZIP文件')
    return
  }

  if (!selectedZabbixServer.value) {
    ElMessage.warning('请先选择Zabbix服务器')
    return
  }

  try {
    ElMessage.info('正在批量导入模板，请稍候...')

    const formData = new FormData()
    formData.append('file', batchUploadFile.value.raw)

    const response = await monitoringApi.batchImportZabbixTemplates(selectedZabbixServer.value, formData)
    console.log('批量导入响应:', response)

    if (response.data.success) {
      ElMessage.success(response.data.message || '批量导入成功')
      closeBatchImportDialog()
      await loadTemplates() // 重新加载模板列表
    } else {
      ElMessage.error(response.data.message || '批量导入失败')
    }
  } catch (error) {
    console.error('批量导入模板失败:', error)
    ElMessage.error(`批量导入模板失败: ${error.response?.data?.message || error.message}`)
  }
}

// 编辑模板
const editTemplate = (template) => {
  editForm.value = {
    templateid: template.templateid,
    name: template.name,
    description: template.description || '',
    status: template.status?.toString() || '0'
  }
  editDialogVisible.value = true
}

const confirmEdit = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    editLoading.value = true

    const response = await monitoringApi.updateZabbixTemplate(
      selectedZabbixServer.value,
      editForm.value.templateid,
      {
        name: editForm.value.name,
        description: editForm.value.description,
        status: editForm.value.status
      }
    )

    if (response.data.success) {
      ElMessage.success('模板编辑成功')
      editDialogVisible.value = false
      await loadTemplates() // 重新加载模板列表
    } else {
      ElMessage.error(response.data.message || '模板编辑失败')
    }
  } catch (error) {
    console.error('编辑模板失败:', error)
    ElMessage.error('编辑模板失败')
  } finally {
    editLoading.value = false
  }
}

const getItemType = (type: string) => {
  const types = {
    '0': 'Zabbix agent',
    '1': 'SNMPv1 agent',
    '2': 'Zabbix trapper',
    '3': 'Simple check',
    '4': 'SNMPv2 agent',
    '5': 'Zabbix internal',
    '6': 'SNMPv3 agent',
    '7': 'Zabbix agent (active)',
    '8': 'Zabbix aggregate',
    '9': 'Web item',
    '10': 'External check',
    '11': 'Database monitor',
    '12': 'IPMI agent',
    '13': 'SSH agent',
    '14': 'TELNET agent',
    '15': 'Calculated',
    '16': 'JMX agent',
    '17': 'SNMP trap',
    '18': 'Dependent item',
    '19': 'HTTP agent',
    '20': 'SNMP agent',
    '21': 'Script'
  }
  return types[type] || `未知类型(${type})`
}

const getTriggerPriority = (priority: string) => {
  const priorities = {
    '0': '未分类',
    '1': '信息',
    '2': '警告',
    '3': '一般严重',
    '4': '严重',
    '5': '灾难'
  }
  return priorities[priority] || `未知(${priority})`
}

// 获取模板状态显示文本
const getTemplateStatusText = (status) => {
  // Zabbix模板状态值含义：
  // 0 = 启用状态：模板处于正常监控状态
  // 1 = 禁用状态：模板被手动禁用
  // 2 = 未启用状态：模板未启用，功能类似禁用状态
  // 3 = 模板状态：标识这是一个模板（而非主机）

  const statusValue = parseInt(status)

  switch (statusValue) {
    case 0:
      return '已启用'
    case 1:
      return '已禁用'
    case 2:
      return '未启用'
    case 3:
      return '模板'
    default:
      if (status === undefined || status === null || status === '') {
        return '未知状态'
      }
      return `状态${status}`
  }
}

// 获取模板状态CSS类
const getTemplateStatusClass = (status) => {
  const statusValue = parseInt(status)

  switch (statusValue) {
    case 0:
      return 'status-enabled'    // 绿色 - 已启用
    case 1:
    case 2:
      return 'status-disabled'   // 红色 - 禁用/未启用
    case 3:
      return 'status-template'   // 蓝色 - 模板标识
    default:
      return 'status-unknown'    // 灰色 - 未知状态
  }
}

// 生命周期
onMounted(() => {
  loadZabbixServers()
})

// 监听器
watch(selectedZabbixServer, (newVal) => {
  if (newVal) {
    loadTemplates()
    loadHostGroups()
  }
})
</script>

<style scoped>
/* 星空背景 */
.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite;
  opacity: 0.6;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 25px, rgba(255,255,255,0.9), transparent);
  background-repeat: repeat;
  background-size: 300px 150px;
  animation: zoom 40s infinite;
  opacity: 0.4;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, #fff, transparent),
    radial-gradient(1px 1px at 150px 150px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 400px 200px;
  animation: zoom 60s infinite;
  opacity: 0.3;
}

@keyframes zoom {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

/* 主容器 */
.zabbix-templates-container {
  min-height: 100vh;
  position: relative;
}

.content-wrapper {
  position: relative;
  z-index: 1;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 玻璃效果 */
.glass-effect {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  box-shadow:
    0 4px 16px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

/* 页面标题 */
.page-header {
  padding: 24px;
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.header-content h1 {
  color: #ffffff;
  font-size: 28px;
  margin: 0;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-content h1 i {
  color: #a4f4ba;
  font-size: 24px;
}

.header-content p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
  margin: 8px 0 0 0;
}

/* 控制面板 */
.control-panel {
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.server-selection {
  display: flex;
  align-items: center;
  gap: 12px;
}

.server-selection label {
  color: #ffffff;
  font-weight: 500;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 玻璃按钮 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.glass-button:hover:not(:disabled) {
  background: rgba(164, 244, 186, 0.25) !important;
  border-color: rgba(164, 244, 186, 0.5) !important;
  color: #ffffff !important;
  box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  transform: translateY(-1px);
}

.glass-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.glass-button i {
  margin-right: 6px !important;
}

.glass-button.primary {
  background: rgba(64, 158, 255, 0.3) !important;
  border-color: rgba(64, 158, 255, 0.5) !important;
}

.glass-button.primary:hover:not(:disabled) {
  background: rgba(64, 158, 255, 0.4) !important;
  border-color: rgba(64, 158, 255, 0.6) !important;
}

/* 刷新按钮 - 紫色 */
.refresh-button {
  background: rgba(138, 43, 226, 0.2) !important;
  border-color: rgba(138, 43, 226, 0.4) !important;
}

.refresh-button:hover:not(:disabled) {
  background: rgba(138, 43, 226, 0.3) !important;
  border-color: rgba(138, 43, 226, 0.6) !important;
  box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
}

/* 创建按钮 - 绿色 */
.create-button {
  background: rgba(34, 197, 94, 0.2) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;
  color: #22c55e !important;
}

.create-button:hover:not(:disabled) {
  background: rgba(34, 197, 94, 0.3) !important;
  border-color: rgba(34, 197, 94, 0.6) !important;
  box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
}

.refresh-button i {
  color: #8a2be2 !important;
}

/* 创建按钮 - 绿色 */
.create-button {
  background: rgba(34, 197, 94, 0.2) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;
}

.create-button:hover:not(:disabled) {
  background: rgba(34, 197, 94, 0.3) !important;
  border-color: rgba(34, 197, 94, 0.6) !important;
  box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
}

.create-button i {
  color: #22c55e !important;
}

/* 导入按钮 - 蓝色 */
.import-button {
  background: rgba(59, 130, 246, 0.2) !important;
  border-color: rgba(59, 130, 246, 0.4) !important;
}

.import-button:hover:not(:disabled) {
  background: rgba(59, 130, 246, 0.3) !important;
  border-color: rgba(59, 130, 246, 0.6) !important;
  box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
}

.import-button i {
  color: #3b82f6 !important;
}

/* 批量导入按钮 - 紫色 */
.batch-import-button {
  background: rgba(147, 51, 234, 0.2) !important;
  border-color: rgba(147, 51, 234, 0.4) !important;
}

.batch-import-button:hover:not(:disabled) {
  background: rgba(147, 51, 234, 0.3) !important;
  border-color: rgba(147, 51, 234, 0.6) !important;
  box-shadow: 0 4px 16px rgba(147, 51, 234, 0.3) !important;
}

.batch-import-button i {
  color: #9333ea !important;
}

/* 导出按钮 - 橙色 */
.export-button {
  background: rgba(245, 158, 11, 0.2) !important;
  border-color: rgba(245, 158, 11, 0.4) !important;
}

.export-button:hover:not(:disabled) {
  background: rgba(245, 158, 11, 0.3) !important;
  border-color: rgba(245, 158, 11, 0.6) !important;
  box-shadow: 0 4px 16px rgba(245, 158, 11, 0.3) !important;
}

.export-button i {
  color: #f59e0b !important;
}

/* 筛选面板 */
.filter-panel {
  padding: 20px;
  margin-bottom: 20px;
}

.search-controls {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  align-items: center;
}

/* 模板内容区域 */
.templates-content {
  margin-bottom: 20px;
}

/* 骨架屏 */
.skeleton-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.skeleton-card {
  padding: 20px;
  height: 200px;
}

.skeleton-header {
  margin-bottom: 16px;
}

.skeleton-text {
  height: 12px;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0.1) 25%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0.1) 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 6px;
  margin-bottom: 8px;
}

.skeleton-title {
  width: 70%;
  height: 16px;
}

.skeleton-subtitle {
  width: 50%;
  height: 12px;
}

.skeleton-short {
  width: 30%;
}

@keyframes skeleton-loading {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
  color: #a4f4ba;
}

.empty-state p {
  font-size: 16px;
  margin: 8px 0;
}

.empty-state .hint {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.4);
}

/* 模板网格 */
.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
}

/* 模板卡片 */
.template-card {
  padding: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
  border-color: rgba(164, 244, 186, 0.3);
}

.template-card.selected {
  border-color: rgba(164, 244, 186, 0.6);
  background: rgba(164, 244, 186, 0.05);
}

.template-card.selected::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: #a4f4ba;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.template-info {
  flex: 1;
  margin-right: 12px;
}

.template-name {
  color: #ffffff;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  line-height: 1.3;
}

.template-description {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.template-status {
  flex-shrink: 0;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-enabled {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a;
  border: 1px solid rgba(103, 194, 58, 0.3);
}

.status-disabled {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
  border: 1px solid rgba(245, 108, 108, 0.3);
}

.status-template {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.status-unknown {
  background: rgba(156, 163, 175, 0.2);
  color: #9ca3af;
  border: 1px solid rgba(156, 163, 175, 0.3);
}

/* 模板统计 */
.template-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
}

.stat-item i {
  color: #a4f4ba;
  width: 14px;
}

/* 模板操作 */
.template-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.action-btn {
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  color: #ffffff;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 90px;
  justify-content: center;
  white-space: nowrap;
  flex: 1;
}

.action-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.15);
  color: #ffffff;
  transform: translateY(-1px);
}

.action-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

/* 查看按钮 - 蓝色 */
.view-btn {
  background: rgba(64, 158, 255, 0.2) !important;
  border-color: rgba(64, 158, 255, 0.4) !important;
}

.view-btn:hover:not(:disabled) {
  background: rgba(64, 158, 255, 0.3) !important;
  border-color: rgba(64, 158, 255, 0.6) !important;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3) !important;
}

.view-btn i {
  color: #409eff !important;
}

/* 编辑按钮 - 橙色 */
.edit-btn {
  background: rgba(230, 162, 60, 0.2) !important;
  border-color: rgba(230, 162, 60, 0.4) !important;
}

.edit-btn:hover:not(:disabled) {
  background: rgba(230, 162, 60, 0.3) !important;
  border-color: rgba(230, 162, 60, 0.6) !important;
  box-shadow: 0 4px 16px rgba(230, 162, 60, 0.3) !important;
}

.edit-btn i {
  color: #e6a23c !important;
}

/* 克隆按钮 - 绿色 */
.clone-btn {
  background: rgba(103, 194, 58, 0.2) !important;
  border-color: rgba(103, 194, 58, 0.4) !important;
}

.clone-btn:hover:not(:disabled) {
  background: rgba(103, 194, 58, 0.3) !important;
  border-color: rgba(103, 194, 58, 0.6) !important;
  box-shadow: 0 4px 16px rgba(103, 194, 58, 0.3) !important;
}

.clone-btn i {
  color: #67c23a !important;
}

/* 导出按钮 - 蓝色 */
.export-btn {
  background: rgba(64, 158, 255, 0.2) !important;
  border-color: rgba(64, 158, 255, 0.4) !important;
}

.export-btn:hover:not(:disabled) {
  background: rgba(64, 158, 255, 0.3) !important;
  border-color: rgba(64, 158, 255, 0.6) !important;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3) !important;
}

.export-btn i {
  color: #409eff !important;
}

/* 删除按钮 - 红色 */
.delete-btn {
  background: rgba(245, 108, 108, 0.2) !important;
  border-color: rgba(245, 108, 108, 0.4) !important;
}

.delete-btn:hover:not(:disabled) {
  background: rgba(245, 108, 108, 0.3) !important;
  border-color: rgba(245, 108, 108, 0.6) !important;
  box-shadow: 0 4px 16px rgba(245, 108, 108, 0.3) !important;
}

.delete-btn i {
  color: #f56c6c !important;
}

/* 关联主机 */
.linked-hosts {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 12px;
}

.hosts-title {
  color: rgba(255, 255, 255, 0.8);
  font-size: 13px;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.hosts-list {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.host-tag {
  background: rgba(164, 244, 186, 0.15);
  color: #a4f4ba;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  border: 1px solid rgba(164, 244, 186, 0.2);
}

.more-hosts {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.6);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  border: 1px solid rgba(255, 255, 255, 0.15);
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  margin-bottom: 60px; /* 避免被footer挡住 */
}

/* 透明玻璃对话框样式 */
.glass-dialog {
  backdrop-filter: blur(10px);
}

.glass-dialog .el-dialog {
  background: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.glass-dialog .el-dialog__header {
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
}

.glass-dialog .el-dialog__title {
  color: #ffffff;
  font-weight: 600;
}

.glass-dialog .el-dialog__body {
  background: transparent;
  padding: 24px;
}

/* 透明玻璃表单样式 */
.glass-form .el-form-item__label {
  color: #ffffff !important;
  font-weight: 500;
}

.glass-input .el-input__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.glass-input .el-input__inner {
  color: #ffffff !important;
  background: transparent !important;
}

.glass-input .el-textarea__inner {
  color: #ffffff !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.glass-select .el-select__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.glass-select .el-select__placeholder {
  color: rgba(255, 255, 255, 0.6) !important;
}

.glass-select .el-select__selected-item {
  color: #ffffff !important;
}

.template-detail-content {
  color: #ffffff;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  color: #a4f4ba;
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
  padding-bottom: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
  font-weight: 500;
}

.info-item span {
  color: #ffffff;
  font-size: 14px;
}

.text-success {
  color: #67c23a !important;
}

.text-danger {
  color: #f56c6c !important;
}

/* 监控项、触发器和图形列表 */
.items-list, .triggers-list, .graphs-list {
  max-height: 300px;
  overflow-y: auto;
}

.item-row, .trigger-row, .graph-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.item-info, .trigger-info, .graph-info {
  flex: 1;
  margin-right: 12px;
}

.item-name, .trigger-name, .graph-name {
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.item-key, .trigger-expression, .graph-id {
  color: #a4f4ba;
  font-size: 12px;
  font-family: 'Courier New', monospace;
}

.item-type {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  white-space: nowrap;
}

.trigger-priority {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  white-space: nowrap;
}

.priority-0 { background: rgba(144, 147, 153, 0.2); color: #909399; }
.priority-1 { background: rgba(64, 158, 255, 0.2); color: #409eff; }
.priority-2 { background: rgba(230, 162, 60, 0.2); color: #e6a23c; }
.priority-3 { background: rgba(245, 108, 108, 0.2); color: #f56c6c; }
.priority-4 { background: rgba(245, 108, 108, 0.3); color: #f56c6c; }
.priority-5 { background: rgba(245, 108, 108, 0.4); color: #f56c6c; }

.more-items, .more-triggers {
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
  font-size: 13px;
  padding: 8px;
  font-style: italic;
}

.no-items, .no-triggers {
  text-align: center;
  color: rgba(255, 255, 255, 0.5);
  font-size: 14px;
  padding: 20px;
  font-style: italic;
}

/* 导入对话框 */
.import-dialog :deep(.el-dialog) {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.import-dialog :deep(.el-dialog__header) {
  background: rgba(164, 244, 186, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.import-dialog :deep(.el-dialog__title) {
  color: #ffffff;
}

.import-content {
  color: #ffffff;
}

.import-content :deep(.el-upload-dragger) {
  background: rgba(255, 255, 255, 0.05);
  border: 2px dashed rgba(164, 244, 186, 0.3);
  border-radius: 8px;
}

.import-content :deep(.el-upload-dragger:hover) {
  border-color: rgba(164, 244, 186, 0.5);
  background: rgba(164, 244, 186, 0.05);
}

.upload-text {
  text-align: center;
  padding: 20px;
}

.upload-text p {
  margin: 8px 0;
  color: #ffffff;
}

.upload-text em {
  color: #a4f4ba;
  font-style: normal;
}

.upload-hint {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.import-options {
  margin-top: 20px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.import-options :deep(.el-checkbox) {
  color: #ffffff;
  margin-bottom: 8px;
  display: block;
}

.import-options :deep(.el-checkbox__label) {
  color: #ffffff;
}

/* 批量导入对话框 */
.batch-import-dialog :deep(.el-dialog) {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.batch-import-dialog :deep(.el-dialog__header) {
  background: rgba(147, 51, 234, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.batch-import-dialog :deep(.el-dialog__title) {
  color: #ffffff;
}

.batch-import-dialog .import-content :deep(.el-upload-dragger) {
  background: rgba(255, 255, 255, 0.05);
  border: 2px dashed rgba(147, 51, 234, 0.3);
  border-radius: 8px;
}

.batch-import-dialog .import-content :deep(.el-upload-dragger:hover) {
  border-color: rgba(147, 51, 234, 0.5);
  background: rgba(147, 51, 234, 0.05);
}

.batch-import-tips {
  margin-top: 20px;
  padding: 16px;
  background: rgba(147, 51, 234, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(147, 51, 234, 0.2);
}

.batch-import-tips h4 {
  color: #9333ea;
  margin: 0 0 12px 0;
  font-size: 14px;
}

.batch-import-tips ul {
  margin: 0;
  padding-left: 20px;
  color: rgba(255, 255, 255, 0.8);
}

.batch-import-tips li {
  margin-bottom: 6px;
  font-size: 13px;
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .control-panel {
    flex-direction: column;
    align-items: stretch;
  }

  .server-selection {
    justify-content: center;
  }

  .action-buttons {
    justify-content: center;
  }

  .search-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .templates-grid {
    grid-template-columns: 1fr;
  }

  .template-stats {
    justify-content: center;
  }

  .template-actions {
    justify-content: center;
  }
}
</style>
